//
//  OAuthViewController.swift
//  wobo
//
//  Created by 杨博宇 on 16/3/9.
//  Copyright © 2016年 杨博宇. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    //关闭界面
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //设置默认用户信息
    @objc private func defaultAccount() {
        
        let jsString = "document.getElementById('userId').value = '13520327391', document.getElementById('passwd').value = '72557by'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
    
    
    override func loadView() {
        
        //1.授权页面的开始,webView 的定义在下面的扩展
        view = webView
        //设置代理
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //1.设置导航条－－－－－－－
        setNavBar()
        view.backgroundColor = UIColor.whiteColor()
        
        //2.加载授权页面－－－－－－－－
        loadOAuthPage()
    }
    
        override func viewWillDisappear(animated: Bool) {
            super.viewWillDisappear(animated)
            SVProgressHUD.dismiss()
        }
    
    //加载授权页面
    private func loadOAuthPage() {
        //1.String
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=\(client_id)" + "&redirect_uri=\(redirect_uri)"
        //2.NSURL
        let url = NSURL(string: urlString)
        //3.NSURLRequest
        let request = NSURLRequest(URL: url!)
        
        webView .loadRequest(request)
    }
    //设置导航条
    private func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试帐号", style: .Plain, target: self, action: "defaultAccount")
    }
    
    
}

//webView协议方法的专门扩展
extension OAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    //定义webView
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //打印回调的地址
        //        print(request.URL)
        
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        
        //包含了回调地址的url中一定包好了code字段
        if urlString.containsString("code") {
            
            //在这个地方需要获取url中包好的code  使用code 获取token
            guard let query = request.URL?.query else {
               return false
            }
            
            let codeStr = "code="
            //将string转换为NSString
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            
            print(query,code)
            
            //使用code来获取token－－－－－－－－
            
            UserAccount.shareAccount.loadAccessToken(code, finished: { (isSuccess) -> () in
                if !isSuccess {
                    SVProgressHUD.showErrorWithStatus("没有网络")
                    return
                }
                //登陆成功 销毁当前页   类于类之间的通信
//                self.close()
                
//                UIApplication.sharedApplication().keyWindow?.rootViewController = WelcomeViewController()
                
            })
            
            self.dismissViewControllerAnimated(true, completion: { () -> Void in
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: "oauth")
            })
                         
            return false
        }
        
        return true
    }
    
    
}








